import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:ldyxiangmu/bean/home_banner_bean.dart';
import 'package:ldyxiangmu/bean/home_bottom_goods_bean.dart';
import 'package:ldyxiangmu/bean/home_hot_goods_bean.dart';
import 'package:ldyxiangmu/bean/home_top_navigator_bean.dart';
import 'package:ldyxiangmu/config/service_url.dart';
import 'package:ldyxiangmu/provide/child_category.dart';
import 'package:ldyxiangmu/router/application.dart';
import 'package:ldyxiangmu/service/service_method.dart';
import 'package:provide/provide.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  //用于更页面的page
  int page = 1;
  List<HomeBottomGoodsBean> bottomGoodsList = [];

  //火爆专区的标题
  Widget hotTitle = Container(
    margin: EdgeInsets.only(top: 10.0),
    padding: EdgeInsets.all(5.0),
    alignment: Alignment.centerLeft,
    decoration: BoxDecoration(
        color: Colors.white,
        border: Border(bottom: BorderSide(width: 1.0, color: Colors.black12))),
    child: Text(
      '火爆专区',
      style: TextStyle(color: Colors.pink),
    ),
  );

  //火爆专区的子项
  Widget _hotWrapList() {
    if (bottomGoodsList.length != 0) {
      List<Widget> listItemWidget = bottomGoodsList.map((val) {
        return InkWell(
          onTap: () {
            Application.router.navigateTo(context,
                '/detail?id=${val.goods_id}');
          },
          child: Container(
            width: ScreenUtil().setWidth(372),
            color: Colors.white,
            padding: EdgeInsets.all(5.0),
            margin: EdgeInsets.only(bottom: 3.0),
            child: Column(
              children: [
                Image.network(
                  val.goods_image_url,
                  width: ScreenUtil().setWidth(375),
                ),
                Text(
                  val.goods_name,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: Colors.pink, fontSize: ScreenUtil().setSp(26)),
                ),
                Row(
                  children: [
                    Text('团购价:¥${val.coupon_price / 100}'),
                    Text(
                      '原价:¥${val.min_group_price / 100}',
                      style: TextStyle(
                          color: Colors.black26,
                          decoration: TextDecoration.lineThrough),
                    )
                  ],
                )
              ],
            ),
          ),
        );
      }).toList();

      return Wrap(
        spacing: 2,
        children: listItemWidget,
      );
    } else {
      return Text('加载中');
    }
  }

  //火爆专区的组合
  Widget _bottomGoods() {
    return Container(
      child: Column(
        children: [hotTitle, _hotWrapList()],
      ),
    );
  }

  @override
  void initState() {
    _getBottomGoods();
    super.initState();
  }

  void _getBottomGoods() {
    var formData = {'page': page};
    request('homeBottomGoods', formData).then((value) {
      List<HomeBottomGoodsBean> newList = HomeBottomGoodsResult.fromJson(value)
          .entity
          .goods_search_response
          .goods_list;
      setState(() {
        bottomGoodsList.addAll(newList);
        page++;
      });
    });
  }

  @override
  // ignore: must_call_super
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334); //以IPhone6尺寸为基准,设计图尺寸
    return Scaffold(
        appBar: AppBar(
          title: Text('百姓生活+'),
        ),
        body: EasyRefresh(
          onRefresh: () async {},
          onLoad: () async {
            _getBottomGoods();
          },
          header: ClassicalHeader(
              bgColor: Colors.white,
              textColor: Colors.pink,
              infoColor: Colors.pink,
              showInfo: true,
              noMoreText: '',
              infoText: '刷新中',
              refreshText: '下拉刷新',
              refreshingText: '正在刷新',
              refreshedText: '刷新完成',
              refreshReadyText: '下拉刷新'),
          footer: ClassicalFooter(
              bgColor: Colors.white,
              textColor: Colors.pink,
              infoColor: Colors.pink,
              showInfo: true,
              noMoreText: '',
              infoText: '刷新中',
              loadText: '下拉刷新',
              loadingText: '正在刷新',
              loadedText: '刷新完成',
              loadReadyText: '下拉刷新'
          ),
          child: SingleChildScrollView(
            child: Column(
              children: [
                FutureBuilder(
                  future: request('homePageBanner', null),
                  builder: (context, val) {
                    if (val.hasData) {
                      List<HomeBannerBean> homeBannerList =
                          HomeBannerResult.fromJson(val.data).entity;
                      return SwiperDiy(
                        swiperDataList: homeBannerList,
                      );
                    } else {
                      return Center(
                        child: Text('加载中'),
                      );
                    }
                  },
                ),
                FutureBuilder(
                    future: request('homeTopNavigator', null),
                    builder: (context, val) {
                      if (val.hasData) {
                        List<HomeTopNavigatorBean> topNavigatorList =
                            HomeTopNavigatorResult.fromJson(val.data).entity[0];
                        return TopNavigator(
                          navigatorList: topNavigatorList,
                        );
                      } else {
                        return Center(
                          child: Text('加载中'),
                        );
                      }
                    }),
                FutureBuilder(
                    future: request('homeTopNavigator', null),
                    builder: (context, val) {
                      if (val.hasData) {
                        List<HomeTopNavigatorBean> topNavigatorList =
                            HomeTopNavigatorResult.fromJson(val.data).entity[1];
                        return TopNavigator(
                          navigatorList: topNavigatorList,
                        );
                      } else {
                        return Center(
                          child: Text('加载中'),
                        );
                      }
                    }),
                FutureBuilder(
                    future: request('homeHotGoods', null),
                    builder: (context, val) {
                      if (val.hasData) {
                        List<HotGoodsBean> hotGoodsList =
                            HomeHotGoodsResult.fromJson(val.data)
                                .entity
                                .goods_search_response
                                .goods_list;
                        return HotGoodsWidget(
                          goodsList: hotGoodsList,
                        );
                      } else {
                        return Center(
                          child: Text('加载中'),
                        );
                      }
                    }),
                _bottomGoods()
              ],
            ),
          ),
        ));
  }

  @override
  bool get wantKeepAlive => true;
}

//轮播图组件
class SwiperDiy extends StatelessWidget {
  final List<HomeBannerBean> swiperDataList;

  const SwiperDiy({Key key, this.swiperDataList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(333),
      width: ScreenUtil().setWidth(750),
      child: Swiper(
        itemBuilder: (context, index) {
          return Image.network(
            '${baseUrl + swiperDataList[index].imagesUrl}',
            fit: BoxFit.fill,
          );
        },
        itemCount: swiperDataList.length,
        pagination: SwiperPagination(), //控制轮播图的小圆点
        autoplay: true,
      ),
    );
  }
}

//导航栏控件
class TopNavigator extends StatelessWidget {
  final List<HomeTopNavigatorBean> navigatorList;

  const TopNavigator({Key key, this.navigatorList}) : super(key: key);

  //girdView的item布局
  Widget _girdViewItemUI(context, HomeTopNavigatorBean item) {
    return InkWell(
      onTap: () {
        print('点击了导航:${item.opt_id}');
      },
      child: Column(
        children: [
          Image.network(
            '${baseUrl + item.imagesUrl}',
            width: ScreenUtil().setWidth(95),
          ),
          Text('${item.title}')
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(180),
      padding: EdgeInsets.all(3.0),
      child: GridView.count(
        physics: NeverScrollableScrollPhysics(),
        crossAxisCount: 5,
        padding: EdgeInsets.all(4.0),
        //拿到数据集合后,将它迭代,把其中的每个数值赋值给UI的item,再形成一个集合
        children:
            navigatorList.map((it) => _girdViewItemUI(context, it)).toList(),
      ),
    );
  }
}

//热销商品组件
class HotGoodsWidget extends StatelessWidget {
  final List<HotGoodsBean> goodsList;

  const HotGoodsWidget({Key key, this.goodsList}) : super(key: key);

  //热销商品的标题
  Widget _titleWidget() {
    return Container(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.fromLTRB(10.0, 2.0, 0, 5.0),
      decoration: BoxDecoration(
          color: Colors.white,
          border:
              Border(bottom: BorderSide(width: 1.0, color: Colors.black12))),
      child: Text(
        '热销商品',
        style: TextStyle(color: Colors.pink),
      ),
    );
  }

  //热销商品的item
  Widget _item(HotGoodsBean hotGoodsBean) {
    return InkWell(
      onTap: () {},
      child: Container(
        height: ScreenUtil().setHeight(330),
        width: ScreenUtil().setWidth(250),
        padding: EdgeInsets.all(8.0),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border(left: BorderSide(width: 1.0, color: Colors.black12)),
        ),
        child: Column(
          children: [
            Image.network(
              '${hotGoodsBean.goods_image_url}',
              fit: BoxFit.fill,
            ),
            Text('团购价:¥${hotGoodsBean.coupon_price / 100}元'),
            Text(
              '原价:¥${hotGoodsBean.min_group_price / 100}元',
              style: TextStyle(
                  decoration: TextDecoration.lineThrough, color: Colors.grey),
            )
          ],
        ),
      ),
    );
  }

  //横向列表的组件
  Widget _hotGoodsList() {
    return Container(
      height: ScreenUtil().setHeight(330),
      child: ListView.builder(
        itemBuilder: (context, index) {
          return _item(goodsList[index]);
        },
        itemCount: goodsList.length,
        scrollDirection: Axis.horizontal,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(400),
      margin: EdgeInsets.only(top: 10.0),
      child: Column(
        children: [_titleWidget(), _hotGoodsList()],
      ),
    );
  }
}
